package com.link.base.base.user.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.user.model.User;
import com.link.base.base.user.service.UserImpService;
import com.link.base.base.user.service.UserService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.CallParam;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.modules.imports.ImportReader;
import com.link.core.modules.imports.ImportsFactory;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author unknown
 * @date unknown
 * @comments 用户
 */
@Controller
@RequestMapping("/link/userImp")
public class UserImpController extends BasicController<User> {

    @Resource
    private UserImpService userImpService;

    @Resource
    private UserService userService;

    /*@Resource
    private LdapShaPasswordEncoder passwordEncoder;*/

    @Resource
    private KeyGenerateService keyGenerateService;

    @Override
    public BasicService<User> getBasicService() {
        return userImpService;
    }

    @Override
    @RequestMapping(value = "/importData")
    @ResponseBody
    public Map<String, Object> importData(User record, QueryParams qps, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("importData")
                .withMessage("导入用户列表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            ImportReader importReader = ImportsFactory.newInstance(qps, request);
            List<User> list = importReader.readList(User.class);
            User user;
            for (int i = 0; list != null && i < list.size(); i++) {
                user = list.get(i);
                User checkUser1 = userImpService.queryByUsername(user.getUsername());
                User checkUser2 = userService.getUserByUsername(user.getUsername());
                if (checkUser1 != null || checkUser2 != null) {
                    result.put("success", false);
                    result.put("result", "导入失败！不能重复创建用户名：" + user.getUsername());
                    return result;
                }
                //String encodedNewPassword = PasswordUtil.generatePwd("111111");//passwordEncoder.encodePassword("111111",null);
                //record.setPassword(encodedNewPassword);
                user.setId(keyGenerateService.keyGenerate());
                userImpService.insert(user);
            }
            result.put("success", true);
            if (list != null) {
                result.put("total", list.size());
            } else {
                result.put("total", 0);
            }

        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @Override
    @RequestMapping(value = "/upsert")
    @ResponseBody
    public Map<String, Object> upsert(@JsonParam User record, HttpSession session,
                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            User checkUser1 = userImpService.queryByUsername(record.getUsername());
            User checkUser2 = userService.getUserByUsername(record.getUsername());
            Long selectId = record.getId();
            if (checkUser1 != null) {
                Long recordId = checkUser1.getId();
                if (!selectId.equals(recordId)) {
                    result.put("success", false);
                    result.put("result", "用户名：" + record.getUsername() + "已存在，不能重复创建！");
                    return result;
                }
            }
            if (checkUser2 != null) {
                result.put("success", false);
                result.put("result", "用户名：" + record.getUsername() + "已存在，不能重复创建！");
                return result;
            }
            String base = "base";
            if (!getBasicService().isInsertFlag(record) && !checkExistDataCache(base, session, record)) {
                throw new ServiceException("PUBLIC-002");
            }
            String newStr = "NEW";
            if (StringUtils.equals(record.getRow_status(), newStr)) {
                //record.setPassword(encodedNewPassword);
                // 不能设置默认密码
            }
            getBasicService().upsert(record);
            User newEntry = getBasicService().queryById(record);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;

    }

    @Override
    public void beforQueryAllOrExample(User entity, HttpServletRequest request) throws Exception {
        CoreUser user = UserUtil.getUser();
        if (entity.getConditionSql() == null) {
//          entity.setConditionSql("");
        }
//      entity.setConditionSql(entity.getConditionSql()+" and createdBy="+"'"+user.getId()+"'");
        Filter filter = new Filter("createdBy", String.valueOf(user.getId()));
        List<Filter> filterList = new ArrayList<Filter>();
        filterList.add(filter);
        entity.setFilterList(filterList);
    }

    @RequestMapping(value = "/check", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> check(@JsonParam CallParam callParam, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            userImpService.runUserCheck(callParam);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/userImpInsert", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> userImpInsert(@JsonParam CallParam callParam, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            userImpService.runNewUserForimp(callParam);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
